package org.sy.lab.多线程基础._2_同步._2_ReentrantLock._4_使用条件;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Counter {
	
	private int beer = 0;
	private int max = 3;
	private Lock lock = new ReentrantLock(false);
	private Condition set = lock.newCondition();
	private Condition get = lock.newCondition();
	private boolean open = true;
	
	public void setBeer() {
		lock.lock();
		try {
			while(beer == max) {
				set.await();
			}
			beer++;
			get.signalAll();
			System.out.println(Thread.currentThread().getName() + "拿出1瓶酒，吧台老酒数量：" + beer);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public void getBeer() {
		lock.lock();
		try {
			while(beer == 0) {
				get.await();
			}
			beer--;
			set.signalAll();
			System.out.println("--" + Thread.currentThread().getName() + "喝掉1瓶酒，吧台老酒数量：" + beer);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
	public boolean hasBeer() {
		return beer>0 ? true:false;
	}

	public boolean isOpen() {
		return open;
	}

	public void setOpen(boolean open) {
		this.open = open;
	}
}
